package cn.ffcs.bpmpvc.svc;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import cn.ffcs.bpm.model.ProcTranRecord;
import cn.ffcs.bpm.model.ProcessConfig;
import cn.ffcs.bpm.model.ProcessConfigDetail;
import cn.ffcs.bpm.model.TransactProcessStatus;
import cn.ffcs.bpmpvc.dao.FlowPvcDao;
import cn.ffcs.bpmpvc.exception.FlowPvcException;
import cn.ffcs.bpmpvc.model.BpmSwimlane;
import cn.ffcs.bpmpvc.web.views.ProcessInstView;
import cn.ffcs.bpmpvc.web.views.ProcessView;
import cn.ffcs.organ.model.Person;

public class ProcessPvcServiceImpl implements ProcessPvcService
{
    private FlowPvcDao flowPvcDao;
    private TaskService taskService;
    public ProcessView getInitProcessInfo(String processId){
    	return getInitProcessInfo(processId,null,null);
    }
    public ProcessView getInitProcessInfo(String processId,String nextNodCondition,Object assignCondition){
        ProcessView processView=new ProcessView();
        ProcessConfig processConfig=getFlowPvcDao().getProcessConfig(processId);
        if(processConfig==null){
            throw new FlowPvcException("未找到相关配置流程配置");
        }
        //取得开始节点
        ProcessConfigDetail startNode=getFlowPvcDao().getProcessStartNode(processId);
        processView.setProcessConfig(processConfig);
        processView.setStartNode(startNode);
        List childNodelistAll=getTaskService().findNextTaskNodes(startNode.getId());
        List childNodelist=null;
        if(StringUtils.isNotBlank(nextNodCondition)){
        	childNodelist=new ArrayList();
        	for (Object object : childNodelistAll)
            {
        		ProcessConfigDetail configDetail=(ProcessConfigDetail)object;
            	if(nextNodCondition.equalsIgnoreCase(configDetail.getCondition())){
            		childNodelist.add(configDetail);
            	}
            }
        }else{
        	childNodelist=childNodelistAll;
        }
        
        processView.setChildTaskNodeList(childNodelist);
        //取权限角色下拉用户
        for (Object object : childNodelist)
        {
            ProcessConfigDetail configDetail=(ProcessConfigDetail)object;
            
            if(configDetail.getPerson()==null){
                if(StringUtils.isNotBlank(configDetail.getSecRole())){
                    List<Person> perSonList=getFlowPvcDao().findPersonByRoleName(configDetail.getSecRole(),true);
                    configDetail.setPersonList(perSonList);
                }else if(StringUtils.isNotBlank(configDetail.getAssignHandlerClass())){
                	try {
                		//System.out.println(assignCondition);
						TaskAssignHandler assignHandler=(TaskAssignHandler)Class.forName(configDetail.getAssignHandlerClass()).newInstance();
						List<Person> perSonList=assignHandler.executeAssign(null,assignCondition);
						configDetail.setPersonList(perSonList);
					} catch (InstantiationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                }
            }
        }
        List documentTypes=getFlowPvcDao().findDocumentTypeByNodeId(startNode.getId());
        processView.setDocumentTypes(documentTypes);
        return processView;
    }
    
    public ProcessInstView startProcessInst(String processId, String userId)
    {
        // TODO Auto-generated method stub
        Person person=new Person();
        person.setId(Integer.parseInt(userId));
        return startProcessInst(processId,person);
    }
    
    
    public ProcessInstView startProcessInst(String processId, Person person)
    {
        // TODO Auto-generated method stub
        return startProcessInst(processId,person,null,false);
    }
    
    public ProcessInstView startProcessInst(String processId, Person person,List<TaskAssignBean> nextTasksList,boolean isCommit){
    	return startProcessInst(processId,person,nextTasksList,isCommit,null);
    }
    public ProcessInstView startProcessInst(String processId, Person person,List<TaskAssignBean> nextTasksList,boolean isCommit,String startSwimPersonId){
        
        ProcessConfig processConfig=getFlowPvcDao().getProcessConfig(processId);
        if(processConfig==null){
            throw new FlowPvcException("未找到相关配置流程配置");
        }
        ProcessInstView processInstView=new ProcessInstView();
        //取得开始节点
        ProcessConfigDetail startNode=getFlowPvcDao().getProcessStartNode(processId);
        
        //保存流程信息
        TransactProcessStatus processStatus=new TransactProcessStatus();
        processStatus.setBegin(new Date());
        processStatus.setCurrProcessConfig(processConfig);
        processStatus.setCurrProcessConfigDetail(startNode);
        processStatus.setState(ProcessPvcService.ACTIVE_ROOT);
       
        getFlowPvcDao().save(processStatus);
        processStatus.setProcinstId(processStatus.getId());
        //写入任务记录
        ProcTranRecord procTranRecord=new ProcTranRecord();
        procTranRecord.setTransactor(person);
        procTranRecord.setReceiveTime(new Date());
        procTranRecord.setTransactInfo("ok");
        procTranRecord.setProcessConfig(processConfig);
        procTranRecord.setProcessStep(startNode);
        procTranRecord.setProcinstId(processStatus.getId());
        procTranRecord.setState(TaskService.TASK_STATE_ACTIVE);
        procTranRecord.setTaskType(TaskService.TASK_TYPE[0][0]);
        getFlowPvcDao().save(procTranRecord);
        //保存swimlane值
        if(StringUtils.isNotBlank(startNode.getSwinlane())){
            BpmSwimlane bpmSwimlane=getFlowPvcDao().getBpmSwimlane(startNode.getSwinlane(), processStatus.getId());
            if(bpmSwimlane==null){
                bpmSwimlane=new BpmSwimlane();
            }
            if(StringUtils.isNotBlank(startSwimPersonId)){
            	bpmSwimlane.setAssign(startSwimPersonId);
            }else{
            	bpmSwimlane.setAssign(person.getId().toString());
            }
            bpmSwimlane.setSwinlane(startNode.getSwinlane());
            bpmSwimlane.setProcinstId(processStatus.getId());
            getFlowPvcDao().save(bpmSwimlane);
        }
        //end
        processStatus.setActId(procTranRecord.getId());
        //
        //当流程启动，且一下环节只有一个节点时，只需传入用户，节点Id由系统获取。
        if(nextTasksList!=null&&nextTasksList.size()==1){
        	TaskAssignBean taskAssignBean=nextTasksList.get(0);
        	if(StringUtils.isBlank(taskAssignBean.getTaskNodeId())){
        		List<ProcessConfigDetail> childNodelist=getTaskService().findNextTaskNodes(startNode.getId());
        		taskAssignBean.setTaskNodeId(childNodelist.get(0).getId().toString());
        	}
        }        
        
        if(isCommit){
            getTaskService().completeTask(procTranRecord, "", nextTasksList);
        }else{
            getTaskService().saveTaskAssignUser(procTranRecord, "", nextTasksList);
        }
        processInstView.setProcessStatus(processStatus);
        processInstView.setProcTranRecord(procTranRecord);
        return processInstView;
    }
    
    public ProcessInstView getProcessInstView(Integer procInstId){
    	//取得任务列表
        List<ProcTranRecord> flowTaskList=getFlowPvcDao().findTaskList(procInstId);
        //得到流程实例信息
        TransactProcessStatus processStatus=getFlowPvcDao().getProcessExecuteInstById(procInstId);
        ProcessInstView processInstView=new ProcessInstView();
        processInstView.setFlowTaskList(flowTaskList);
        if(processStatus!=null){
	        processStatus.getCurrProcessConfig().getName();
	        processInstView.setProcessConfig(processStatus.getCurrProcessConfig());
	        processInstView.setProcessStatus(processStatus);
        }
    	return processInstView;
    }
    
    public TaskService getTaskService()
    {
        return taskService;
    }


    public void setTaskService(TaskService taskService)
    {
        this.taskService = taskService;
    }


    public void deleteProcessInst(String processInstId)
    {
        // TODO Auto-generated method stub
        
    }

    public FlowPvcDao getFlowPvcDao()
    {
        return flowPvcDao;
    }

    public void setFlowPvcDao(FlowPvcDao flowPvcDao)
    {
        this.flowPvcDao = flowPvcDao;
    }





}
